package com.zjj.algorithm.learning.atguigu.stack;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

/**
 * 实现逆波兰计算器
 * @author zjj_admin
 * @date 2022/11/9 17:20
 */
public class PolandNotation {

    public static void main(String[] args) {
        //(30+4)×5-6  => 30 4 + 5 × 6 - => 164
//        String suffixExpr = "4 5 * 8 - 60 + 8 2 / +";
        String suffixExpr = "10 6 9 3 + -11 * / * 17 + 5 +";
        List<String> list = getStringList(suffixExpr);
        System.out.println("list = " + list);
        int res = calculate(list);
        System.out.println("运算的结果为：" + res);

    }


    /**
     * 将表达式中字符和数字以集合形式返回
     * @param expr
     * @return
     */
    public static List<String> getStringList(String expr){
        String[] split = expr.split(" ");
        ArrayList<String> list = new ArrayList<>();
        for (String ele : split) {
            list.add(ele);
        }
        return list;
    }

    public static int calculate(List<String> list){
        Stack<String> stack = new Stack<>();
        for (String ele : list) {
            if (ele.matches("\\d+")){
                stack.push(ele);
            }else {
                //取出两个数，并入栈
                int num2 = Integer.parseInt(stack.pop());
                int num1 = Integer.parseInt(stack.pop());
                int res = 0;
                if("+".equals(ele)){
                    res = num1 + num2;
                }else if ("-".equals(ele)){
                    res = num1 - num2;
                }else if ("*".equals(ele)){
                    res = num1 * num2;
                }else if ("/".equals(ele)){
                    res = num1 / num2;
                }else {
                    throw new RuntimeException("运算符错误");
                }
                stack.push(res + "");
            }
        }
        return Integer.parseInt(stack.pop());
    }

}
